<template>
  <div class="main-div">
    <div class="main-search-div">
      <el-form
          :model="searchItem"
          ref="searchItemRef"
          label-width="100px"
          label-suffix=":"
          inline
      >
        <el-form-item label="角色名称" prop="roleName" class="main-search-item-3">
          <el-input v-model="searchItem.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType" class="main-search-item-3">
          <el-select v-model="searchItem.roleType" :clearable="true" placeholder="请选择!">
            <el-option v-for="item in roleTypeData" :key="item.key||item.value" :label="item.label"
                       :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述" prop="description" class="main-search-item-3">
          <el-input v-model="searchItem.description"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search" :loading="searchLoading">查询</el-button>
          <el-button @click="reset(searchItemRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="main-button-div">
      <el-button type="primary" @click="addRoleFn">新增</el-button>
      <el-popconfirm title="是否删除?" @confirm="delRoleFn(0)">
        <template #reference>
          <el-button type="danger">删除</el-button>
        </template>
      </el-popconfirm>
    </div>
    <div class="main-table-div">
      <common-page-table
          :data="tableData"
          :columns="columns"
          :pagination="pagination"
          :show-border="true"
          :need-one-select="true"
          :show-no="true"
          :loading="tableLoading"
          :show-action="true"
          :action-config="actionConfig"
          @sizeChange="sizeChange"
          @currentChange="currentChange"
          @handle-current-change="handleTableCurrentChange">
        <template #action="{row}">
            <el-button type="primary" size="small" round @click="editFn(row)">编辑</el-button>
            <el-button type="warning" size="small" round @click="addUserFn(row)">添加用户</el-button>
            <el-button type="warning" size="small" round @click="addMenuFn(row)">添加菜单</el-button>
        </template>
      </common-page-table>
    </div>
  </div>

  <el-dialog v-model="showTip"
             title="提示"
             :destroy-on-close="false"
             :close-on-click-modal="false">
    <span>{{tipContent}}</span>
    <template #footer>
      <el-button type="primary" @click="tipConfirm">确认</el-button>
      <el-button type="danger" @click="tipCancel">取消</el-button>
    </template>
  </el-dialog>
  <role-save-dialog
      :show-dialog="saveDialog.showDialog"
      :title="saveDialog.dialogTitle"
      :dialog-type="saveDialog.dialogType"
      :dialog-param="saveDialog.dialogParam"
      @open-dialog="handleOpenSaveDialog"
      @opened-dialog="handleOpenedSaveDialog"
      @close-dialog="handleCloseSaveDialog($event)"
      @closed-dialog="handClosedSaveDialog($event)"
  >

  </role-save-dialog>
  <relation-transfer :show-dialog="relationTransferUser.showDialog"
                     :title="relationTransferUser.title"
                     :relation-id="relationTransferUser.relationId"
                     :relation-type="relationTransferUser.relationType"
                     @handleOpenDialog="openRelationTransferUser"
                     @handleCloseDialog="closeRelationTransferUser($event)"
                     @confirmRelation="handleConfirmRelationUser($event)"
  >
  </relation-transfer>
  <relation-transfer :show-dialog="relationTransferMenu.showDialog"
                     :title="relationTransferMenu.title"
                     :relation-id="relationTransferMenu.relationId"
                     :relation-type="relationTransferMenu.relationType"
                     @handleOpenDialog="openRelationTransferMenu"
                     @handleCloseDialog="closeRelationTransferMenu($event)"
                     @confirmRelation="handleConfirmRelationMenu($event)"
  >
  </relation-transfer>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref} from "vue";
import type {FormInstance} from "element-plus";
import {dictDataUtil} from '@/utils/common-request'
import {SYSTEM_ROLE_TYPE} from "@/constants/dict-constants.ts";
import CommonPageTable from "@/components/common/CommonPageTable.vue";
import {delRoleReq, getRoleListReq, saveRoleMenuIdsReq, saveRoleUserIdsReq} from "@/api/admin/role.ts";
import {RESPONSE_CODE_SUCCESS, RESPONSE_CODE_TIP_201} from "@/config/common-config.ts";
import {checkIsNull} from "@/utils/check-utils.ts";
import {elMessageTip, errorMessageTip, successMessageTip, warningMessageTip} from "@/utils/tip-utils.ts";
import RoleSaveDialog from "@/components/manager/role/RoleSaveDialog.vue";
import {
  DIALOG_ADD,
  DIALOG_EDIT,
  RELATION_TYPE_ROLE_TO_MENU,
  RELATION_TYPE_ROLE_TO_USER
} from "@/constants/common-constant.ts";
import RelationTransfer from "@/components/manager/relation/RelationTransfer.vue";

interface SearchItem {
  roleName: string,
  roleType: string,
  description: string
}

const searchItem = reactive<SearchItem>({
  roleName: '',
  roleType: '',
  description: ''
})

interface SaveDialog{
  showDialog: boolean;
  dialogTitle: string;
  dialogType: string;
  dialogParam: any;
}

const saveDialog = reactive<SaveDialog>({
  showDialog: false,
  dialogTitle: '',
  dialogType: '',
  dialogParam: {}
})

interface RelationTransferUser {
  showDialog: boolean;
  title: string;
  relationId: string;
  relationType: string;
}

const relationTransferUser = reactive<RelationTransferUser>({
  showDialog: false,
  title: '',
  relationId: '',
  relationType: ''
})

interface RelationTransferMenu {
  showDialog: boolean;
  title: string;
  relationId: string;
  relationType: string;
}

const relationTransferMenu = reactive<RelationTransferMenu>({
  showDialog: false,
  title: '',
  relationId: '',
  relationType: ''
})

const searchItemRef = ref<FormInstance>();
const searchLoading = ref<boolean>(false)
const roleTypeData = ref<any>(() => [])
const tableData = ref<any>([])
const columns = [
  {prop: 'roleName', label: '角色名称', fixed: 'left', width: 'auto'},
  {prop: 'roleTypeLabel', label: '角色类型', width: 'auto'},
  {prop: 'description', label: '角色描述', width: 'auto'},
]
const currentPage = ref<number>(1)
const pageSize = ref<number>(10)
const total = ref<number>(0)
const pagination = reactive({
  currentPage: currentPage.value,
  pageSize: pageSize.value,
  total: total.value
})
const tableLoading = ref<boolean>(false)
const actionConfig = {
  prop: 'action',
  label: '操作',
  width: 'auto',
}
const currentRow = ref()
const sizeChange = (val: number) => {
  pageSize.value = val;
  pagination.pageSize = val;

  searchList().then();
}

const currentChange = (val: number) => {
  currentPage.value = val;
  pagination.currentPage = val;

  searchList().then();
}

const handleTableCurrentChange = (row: any) => {
  currentRow.value = row
}


const initRoleTypeData = async () => {
  roleTypeData.value = await dictDataUtil(SYSTEM_ROLE_TYPE)
}
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const search = async () => {
  currentPage.value = 1
  pagination.currentPage = 1
  searchList().then()
}

const searchList = async () => {
  searchLoading.value = true
  tableLoading.value = true
  const params = {
    pageSize: pageSize.value,
    pageNum: currentPage.value
  }
  const res: any = await getRoleListReq(params)
  if (res.code === RESPONSE_CODE_SUCCESS) {
    searchLoading.value = false
    tableLoading.value = false
    tableData.value = res.data.rows;
    total.value = res.data.total;
    pagination.total = res.data.total;
  }
}

const addRoleFn = () => {
  saveDialog.showDialog = true
  saveDialog.dialogTitle = '新增'
  saveDialog.dialogType = DIALOG_ADD
  saveDialog.dialogParam = {}
}
const showTip = ref<boolean>(false)
const tipContent = ref<string>('')
const delRoleFn = async (secMark: number) => {
  const selectRow = currentRow.value
  if (checkIsNull(selectRow)){
    warningMessageTip("请至少选择一条数据")
    return
  }

  const params = {
    id: selectRow['id'],
    dictionaryKey: selectRow['dictionaryKey'],
    secMark: secMark
  }
  const res: any = await delRoleReq(params);
  if (res.code === RESPONSE_CODE_SUCCESS) {
    searchList().then()
    successMessageTip(res.message)
  } else if (res.code === RESPONSE_CODE_TIP_201){
    showTip.value = true
    tipContent.value = res.message
  } else {
    errorMessageTip(res.message)
  }
}

const editFn = (row: any) => {
  saveDialog.showDialog = true
  saveDialog.dialogTitle = '编辑'
  saveDialog.dialogType = DIALOG_EDIT
  saveDialog.dialogParam = row
}

const addUserFn = (row: any) => {
  relationTransferUser.showDialog = true
  relationTransferUser.title = row.roleName + '分配用户'
  relationTransferUser.relationId = row.id
  relationTransferUser.relationType = RELATION_TYPE_ROLE_TO_USER
}

const addMenuFn = (row: any) => {
  relationTransferMenu.showDialog = true
  relationTransferMenu.title = row.roleName + '分配菜单'
  relationTransferMenu.relationId = row.id
  relationTransferMenu.relationType = RELATION_TYPE_ROLE_TO_MENU
}

const tipCancel = () => {
  showTip.value = false
}

const tipConfirm = async () => {
  showTip.value = false
  await delRoleFn(1);
}

const handleOpenSaveDialog = () => {
}

const handleOpenedSaveDialog = () => {

}

const handleCloseSaveDialog = (val: boolean) => {
  saveDialog.showDialog = val
}

const handClosedSaveDialog = (val: boolean) => {
  saveDialog.showDialog = val
  searchList().then()
}

const openRelationTransferUser = () => {

}

const closeRelationTransferUser = (val: boolean) => {
  relationTransferUser.showDialog = val
}

const handleConfirmRelationUser = async (data: any) => {
  const params = {
    id: data.relationId,
    userList: data.selectInfo
  }
  const res: any = await saveRoleUserIdsReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    relationTransferUser.showDialog = false
  }
}

const openRelationTransferMenu = () => {

}

const closeRelationTransferMenu = (val: boolean) => {
  relationTransferMenu.showDialog = val
}

const handleConfirmRelationMenu = async (data: any) => {
  const params = {
    id: data.relationId,
    menuList: data.selectInfo
  }
  const res: any = await saveRoleMenuIdsReq(params)
  elMessageTip(res.tipType, res.message)
  if (res.code === RESPONSE_CODE_SUCCESS){
    relationTransferMenu.showDialog = false
  }
}

onMounted(async () => {
  initRoleTypeData().then();
  searchList().then();
})
</script>

<style scoped>

</style>